package com.xuexi.demos.utils;

import java.util.Base64;
import java.util.Date;

/**
 * 简单的JWT工具类，避免使用有问题的JWT库
 */
public class SimpleJwtUtils {

    private static final String SECRET = "BuffSiteSecretKeyForJWT@2023!";
    private static final long EXPIRATION = 24 * 60 * 60 * 1000; // 24小时

    /**
     * 生成简单的JWT令牌
     */
    public static String generateToken(String username) {
        try {
            // 创建简单的token格式: username:timestamp:signature
            long currentTime = System.currentTimeMillis();
            long expirationTime = currentTime + EXPIRATION;
            
            // 创建payload
            String payload = username + ":" + currentTime + ":" + expirationTime;
            
            // 使用Base64编码
            String encodedPayload = Base64.getEncoder().encodeToString(payload.getBytes());
            
            // 创建简单的签名
            String signature = createSignature(payload);
            
            // 组合token: payload.signature
            return encodedPayload + "." + signature;
        } catch (Exception e) {
            // 如果生成失败，返回一个简单的token
            return Base64.getEncoder().encodeToString((username + ":" + System.currentTimeMillis()).getBytes());
        }
    }

    /**
     * 验证并解析令牌
     */
    public static String parseToken(String token) {
        try {
            if (token == null || token.isEmpty()) {
                return null;
            }
            
            // 分割token
            String[] parts = token.split("\\.");
            if (parts.length != 2) {
                return null;
            }
            
            String encodedPayload = parts[0];
            String signature = parts[1];
            
            // 解码payload
            String payload = new String(Base64.getDecoder().decode(encodedPayload));
            String[] payloadParts = payload.split(":");
            
            if (payloadParts.length != 3) {
                return null;
            }
            
            String username = payloadParts[0];
            long currentTime = Long.parseLong(payloadParts[1]);
            long expirationTime = Long.parseLong(payloadParts[2]);
            
            // 检查是否过期
            if (System.currentTimeMillis() > expirationTime) {
                return null;
            }
            
            // 验证签名
            String expectedSignature = createSignature(payload);
            if (!signature.equals(expectedSignature)) {
                return null;
            }
            
            return username;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 创建简单的签名
     */
    private static String createSignature(String payload) {
        try {
            // 使用简单的哈希算法创建签名
            int hash = payload.hashCode();
            hash = hash ^ SECRET.hashCode();
            return Base64.getEncoder().encodeToString(String.valueOf(hash).getBytes());
        } catch (Exception e) {
            return "default";
        }
    }
}
